<template>
  <a-modal
    title="选择图表"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-table
        :row-selection="{ onChange: onSelectChange }"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
      >
        <form slot="name" slot-scope="text, record">
          <template v-if="record.editable">
            <a-input :value="text" @change="(e) => handleChange(e.target.value, record.key)" />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </form>
        <div slot="operate" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => saveData(record.key, record)">保存</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定关闭吗?" @confirm="() => cancel(record.key)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => editData(record.key)">编辑</a>
              <a-divider type="vertical" />
              <a :disabled="editingKey !== ''" @click="() => deleteData(record)">删除</a>
            </span>
          </div>
        </div>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlSelect, sqlDelete, sqlUpdate } from '@/api/sql'
import _ from 'lodash'

export default {
  name: 'LogChartListModal',
  data () {
    return {
      visible: false,
      confirmLoading: false,
      editingKey: '',
      pagination: {
        defaultPageSize: 5,
        pageNo: 0,
        pageSize: 5,
        showTotal: (total) => this.$t('pagination.total') + ` ${total} ` + this.$t('pagination.items'),
        total: 0
      },
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '创建时间',
          dataIndex: 'modify_date'
        },
        {
          title: '操作',
          dataIndex: 'operate',
          width: '150px',
          scopedSlots: { customRender: 'operate' }
        }
      ],
      data: [],
      cacheData: [],
      selectedRows: []
    }
  },

  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },

  methods: {
    /**
     * 初始化
     */
    async init () {
      this.visible = true
      const data = await this.getData()
      console.log('data', data)

      this.data = data
      this.cacheData = _.cloneDeep(this.data)
      this.pagination.total = this.data.length

      this.editingKey = ''
    },

    /**
     * 提交表单
     */
    handleSubmit () {
      console.log(this.selectedRows)
      if (!this.selectedRows.length) {
        this.$message.info('请选择要添加的图表后确认')
        return
      }
      this.$bus.emit('selectedChart', this.selectedRows)
      this.visible = false
      this.confirmLoading = false
      this.$notification['success']({
        message: '提示',
        description: '图表添加成功！'
      })
    },

    /**
     * cancel
     */
    handleCancel () {
      this.visible = false
    },

    /**
     * 获取数据
     */
    async getData () {
      const params = {
        sql: `select * from t_log_chart where create_by='${this.userInfo.login}' order by id desc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            res.forEach((item, index) => {
              item.key = index
            })
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    handleChange (value, key) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.key)[0]
      if (target) {
        target['name'] = value
        this.data = newData
      }
    },

    /**
     * 编辑
     */
    editData (key) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    },

    deleteData (record) {
      this.$confirm({
        title: '提示',
        content: '确定删除数据吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.delete(record.id).then((res) => {
            this.$notification['success']({
              message: '提示',
              description: '数据删除成功'
            })
            // 删除选中的行
            this.selectedRows.forEach((item, index) => {
              if (item.id === record.id) {
                this.selectedRows.splice(index, 1)
              }
            })
            // 重新请求数据
            this.init()
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },

    /**
     * 保存
     */
    saveData (key, record) {
      console.log(key)
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter((item) => key === item.key)[0]
      const targetCache = newCacheData.filter((item) => key === item.key)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''

      // 储存到数据库
      this.save(record).then((res) => {
        this.$notification['success']({
          message: '提示',
          description: '数据修改成功'
        })
      })
    },

    /**
     * 储存
     */
    save (record) {
      var params = {
        sql: `update t_log_chart set name='${record.name}',create_by='${this.userInfo.login}', modify_by='${this.userInfo.login}',parameter='${record.parameter}' where id=${record.id}`
      }
      console.log(params)
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /**
     * 删除
     */
    delete (id) {
      const params = {
        sql: `delete from t_log_chart where id=${id}`
      }
      return new Promise((resolve, reject) => {
        sqlDelete(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    cancel (key) {
      const newData = [...this.data]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKey = ''
      if (target) {
        Object.assign(target, this.cacheData.filter((item) => key === item.key)[0])
        delete target.editable
        this.data = newData
      }
    },

    /**
     * 表选择行
     */
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
    }
  }
}
</script>
